package com.example.demo.sys.service.impl;

import java.util.List;
import java.util.ArrayList;

import com.example.demo.core.tree.TreeBuilder;
import com.example.demo.core.utils.BeanConvertor;
import com.example.demo.sys.dao.MenuMapper;
import com.example.demo.sys.entity.Menu;
import com.example.demo.sys.service.MenuService;
import com.example.demo.sys.service.bo.MenuBO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MenuServiceImpl implements MenuService {
	@Autowired
	private MenuMapper menuMapper;
	
	@Override
	public List<MenuBO> getAllMenus() {
		List<Menu> menus = _getMenus();
		return TreeBuilder.convert(menus, 0L, source -> new MenuBO());
	}
	
	private List<Menu> _getMenus() {
		return menuMapper.getAll();
	}
	
	@Override
	public void updateMenu(MenuBO menuBO) {
		Menu menu = BeanConvertor.transfer(menuBO, new Menu());
		menu.setUpdatedAt(System.currentTimeMillis()/1000);
		menuMapper.update(menu);
	}

	@Override
	public void addMenu(MenuBO menuBO) {
		Menu menu = BeanConvertor.transfer(menuBO, new Menu());
		menu.setCreatedAt(System.currentTimeMillis()/1000);
		menuMapper.add(menu);
	}

	@Override
	public void removeMenu(Integer id) {
		List<Menu> menus = _getMenus();
		List<Long> ids = getSubMenuIds(menus, Long.valueOf(id));
		ids.add(Long.valueOf(id));
		menuMapper.removeByIds(ids);
	}

	private List<Long> getSubMenuIds(List<Menu> menus, Long pid) {
		List<Long> ids = new ArrayList<>();
		for(int i=0;i<menus.size();i++) {
			Menu menu = menus.get(i);
			if(menu.getPid()==pid) {
				ids.add(menu.getId());
				ids.addAll(getSubMenuIds(menus, menu.getId()));
			}
		}
		
		return ids;
	}
}
